<template>
	<view class="container">
		<view class="example">
			<textarea v-model="content" maxlength="999999999"
				style="width:100% !important;min-height:700px !important;font-size: 14px !important;" class="textarea"
				type="textarea" placeholder="请输入作业内容" />
		</view>

		<view class="button-group" v-show="openSave">
			<button style="width: 50%;line-height: 3;" size="mini" @click="saveJob('customForm')">保存</button>
			<button type="primary" style="width: 50%;line-height: 3;" size="mini"
				@click="saveAndPublishJob('customForm')">保存并提交</button>
		</view>

		<view>
			<u-toast ref="uToast" />
		</view>
	</view>
</template>


<script>
	import {
		doWork,
		updateWorkInfo
	} from '@/api/jz/class/class.js';
	import {
		getUser,
		getInfoId,
		getToken
	} from '@/utils/auth';
	import config from '@/config'
	export default {
		data() {
			return {
				openSave: true,
				readOnly: false,
				formats: {}, // 多选数据源
				hobbys: [], //多选班级
				teacherId: getInfoId(), //老师id
				isAnnounce: null, //0 保存 ； 1 保存并发布
				content: '',
				// 自定义表单数据
				customFormData: {
					name: '',
					content: "",
					classArr: []
				},
				// 自定义表单校验规则
				customRules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '作业标题不能为空'
						}]
					},
					classArr: {
						rules: [{
								format: 'array'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length < 1) {
										callback('请至少勾选一个班级')
									}
									return true
								}
							}
						]
					}

				},

				workObj: {},

			}
		},
		onLoad(option) {

			if (option.worksObj) {

				let workObj = JSON.parse(decodeURIComponent(option.worksObj))
				console.log('workObj', workObj)
				this.workObj = workObj
				this.content = workObj.map.content

				// this.customFormData.name = workObj.title

				// this.customFormData.classArr = []
				// this.customFormData.classArr.push(workObj.classId)
				// this.customFormData.content = workObj.contents

			}
		},
		mounted() {
			// this.getClassinfo()
		},
		methods: {
			showToast() {
				this.$refs.uToast.show({
					title: '作业内容不能为空',
					type: 'warning',
					// url: '/pages/user/index'
				})
			},
			checkboxGroupChange(val) {
				this.customFormData.classArr = val.detail.value
			},
			async getClassinfo() {
				await getClassInfoByTeacherId().then((res) => {
					this.hobbys = []
					// if (res.code == 200) {
					this.hobbys = res

					this.hobbys = this.hobbys.map(item => {
						return {
							...item,
							text: item.className,
							value: item.id
						}
					})

					// }
				}).catch((err) => {
					console.error(err);
				});
			},

			//

			getNowDate() {
				var myDate = new Date;
				var year = myDate.getFullYear(); //获取当前年
				var mon = myDate.getMonth() + 1; //获取当前月
				var date = myDate.getDate(); //获取当前日
				var hours = myDate.getHours(); //获取当前小时
				var minutes = myDate.getMinutes(); //获取当前分钟
				var seconds = myDate.getSeconds(); //获取当前秒
				var now = year + "-" + mon + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
				return now;
			},

			submit(ref) {
				// this.$refs[ref].validate().then(res => {
				if (this.workObj.wsId) {
					var startTime = ""
					if (this.isAnnounce) {
						startTime = this.getNowDate()
					}
					const data = {
						id: this.workObj.wsId,
						isAnnounce: this.isAnnounce,
						content: this.content,

					}

					updateWorkInfo(data).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: `修改成功`
							})
							setTimeout(function() {
								uni.navigateBack({
									delta: 1
								});
							}, 2000)
						}

					}).catch((err) => {
						console.error(err);
					});
				} else {
					var startTime = ""
					if (this.isAnnounce) {
						startTime = this.getNowDate()
					}
					const data = {
						teacherId: this.workObj.teacherId,
						classCode: this.workObj.classCode,
						classId: this.workObj.classId,
						studentId: getInfoId(),
						isAnnounce: this.isAnnounce,
						content: this.content,
						startTime: startTime,
						workId: this.workObj.id,
					}

					doWork(data).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: `保存成功`
							})
							setTimeout(function() {
								uni.navigateBack({
									delta: 1
								});
							}, 1000)
						}

					}).catch((err) => {
						console.error(err);
					});
				}


			},

			saveJob(ref) {
				this.isAnnounce = 0
				if (this.content) {
					this.submit(ref)
				} else {
					this.showToast()
				}

			},
			saveAndPublishJob(ref) {
				this.isAnnounce = 1
				if (this.content) {
					this.openSave = false;
					this.submit(ref)
				} else {
					this.showToast()
				}
			},


			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			onEditorReady(e) {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
					res.context.setContents({
						html: ""
					})


				}).exec()
				// uni.createSelectorQuery().in(this).select('#editor').fields({
				//   size: true,
				//   context: true
				// }, res => {
				//   // this.editorCtx = res.context;
				//   res.context.setContents({
				//     html: this.content

				//   })
				// })
				//   .exec();

			},
			getText(e) { //获取数据
				var that = this;
				console.log(e);
				getApp().globalData.editor = e.detail.html
				// console.log(e.detail.html);//带标签内容
				that.content = e.detail.html
				// console.log(e.detail.text);//纯文本内容
			},
			undo() {
				this.editorCtx.undo()
			},
			redo() {
				this.editorCtx.redo()
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				this.editorCtx.format(name, value)
			},
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
			clear() {
				this.editorCtx.clear({
					success: function(res) {
						console.log("clear success")
					}
				})
			},
			removeFormat() {
				this.editorCtx.removeFormat()
			},
			insertDate() {
				const date = new Date()
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.editorCtx.insertText({
					text: formatDate
				})
			},
			insertImage() {
				var that = this;
				uni.chooseImage({
					count: 1,
					success: (res) => {
						console.log('insert image success')
						const tempFilePaths = res.tempFilePaths;
						uni.uploadFile({
							url: config.baseUrl + '/system/user/profile/avatar',
							filePath: tempFilePaths[0],
							name: 'avatarfile',
							header: {
								"Authorization": 'Bearer ' + getToken()
							},
							success: (uploadFileRes) => {
								let data = JSON.parse(uploadFileRes.data)
								if (data.code == 200) {
									console.log(config.baseUrl + data.imgUrl)

									that.editorCtx.insertImage({
										src: config.baseUrl + data.imgUrl,
										alt: '图像',
										success: function() {}
									})
								} else {
									that.showToast(back.msg)
								}
							},
							fail: () => {
								uni.hideLoading();
								that.showToast("图片上传失败，请联系开发！")
							}
						});
					}
				})
			}
		}
	}
</script>


<style lang="scss" scoped>
	.textarea {
		display: flex;
		box-sizing: border-box;
		flex-direction: row;
		align-items: center;
		border: 1px solid #dcdfe6;
		// border-radius: 4px;
	}

	.example {
		background-color: #ffffff;
		margin: 20rpx;
		padding: 20rpx;
		// border-radius: 10px;
		border: none;
		box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.04),
			0px 2px 6px 0px rgba(0, 0, 0, 0.04), 0px 0px 1px 0px rgba(0, 0, 0, 0.04);
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
		bottom: 0;
		position: fixed;
		bottom: 0rpx;
		width: 100%;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>

<style>
	/* @import "./editor-icon.css"; */

	.page-body {
		height: 800rpx;
		width: 100%;
		margin: 0 auto;
		border-radius: 12rpx;
		background-color: #ffffff;
	}

	.wrapper {
		height: 300rpx;
	}

	.editor-wrapper {
		background-color: #ffffff;
		height: 500rpx;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		height: 90rpx;
		font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
	}

	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		min-height: 30vh;
		height: 100%;
		font-size: 16px;
		line-height: 1.5;
	}

	.ql-active {
		color: #06c;
	}
</style>